package logic

import (
	"context"
	"github.com/google/uuid"
	"zg6/zg6_month/ordersrv/model"

	"zg6/zg6_month/ordersrv/internal/svc"
	"zg6/zg6_month/ordersrv/ordersrv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *ordersrv.CreateOrderReq) (*ordersrv.CreateOrderRes, error) {
	// todo: add your logic here and delete this line
	order := model.Order{
		OrderSn:    uuid.NewString(),
		TotalPrice: in.TotalPrice,
		Status:     0,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		return nil, err
	}
	for _, v := range in.Goods {
		err = model.DB.Create(&model.OrderDetail{
			OrderSn:  order.OrderSn,
			GoodsId:  int(v.Id),
			GoodsNum: int(v.Num),
		}).Error
		if err != nil {
			return nil, err
		}
	}
	return &ordersrv.CreateOrderRes{
		OrderSn: order.OrderSn,
	}, nil
}
